﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Linq;
using System.Web;
using System.Xml;
using Gollie.WebCache;

namespace Gollie.Menu
{
	public class CachedMenu : CacheFileDependency
	{
		private static string cacheName = "data_menus";
		public MenuCollection Menu;

		public CachedMenu()
			: base(HttpContext.Current.Server.MapPath("/App_Data/Menu.xml"))
		{
			this.Menu = new MenuCollection(this.DependencyPath);
		}

		public static CachedMenu GetInstance()
		{
			return DataCache.GetCacheableObject<CachedMenu>(cacheName);
		}
	}

	public class MenuCollection : Dictionary<string, MainMenu>
	{
		public MenuCollection(string menuPath)
		{
			this.ReadMenus(menuPath);
		}

		private void ReadMenus(string menuPath)
		{
			XmlDocument doc = new XmlDocument();

			doc.Load(menuPath);

			XmlNodeList nodes = doc.SelectNodes("/gollie/menu");

			if (nodes != null)
			{
				foreach (XmlNode node in nodes)
				{
					string type = node.Attributes["type"].Value;
					string direction = node.Attributes["direction"].Value;
					string css = null;
					string submenuCss = null;
					string separatorCss = null;

					MenuDirection menuDirection = (direction == "vertical" ? MenuDirection.Vertical : MenuDirection.Horizontal);

					XmlAttribute attr = node.Attributes["css"];
					if (attr != null)
						css = attr.Value;

					attr = node.Attributes["submenucss"];
					if (attr != null)
						submenuCss = attr.Value;

					attr = node.Attributes["separatorcss"];
					if (attr != null)
						separatorCss = attr.Value;

					MainMenu mainMenu = new MainMenu(type, menuDirection, css, submenuCss, separatorCss);

					mainMenu.Populate(node);

					mainMenu.RenderHtml();

					this[type] = mainMenu;
				}
			}

			doc.RemoveAll();
		}

	}
}